package utils

import (
	"fmt"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/transport/http"
	"log"
	"os"
	"os/exec"
)

func main() {
	repoPath := "./my-repo"
	repoURL := "https://gitlab.com/your-repo/your-project.git"
	branch := "your-branch"
	auth := &http.BasicAuth{
		Username: "your-username", // 只需任意非空字符串
		Password: "your-personal-access-token",
	}

	if _, err := os.Stat(repoPath); os.IsNotExist(err) {
		fmt.Println("Directory does not exist, initializing repository...")
		// Clone the repository
		_, err := git.PlainClone(repoPath, false, &git.CloneOptions{
			URL:           repoURL,
			ReferenceName: plumbing.NewBranchReferenceName(branch),
			Auth:          auth,
			Progress:      os.Stdout,
		})
		if err != nil {
			log.Fatalf("Failed to clone repository: %v", err)
		}
	} else {
		fmt.Println("Directory exists, opening repository...")
		// Open the existing repository
		repo, err := git.PlainOpen(repoPath)
		if err != nil {
			log.Fatalf("Failed to open repository: %v", err)
		}

		// Fetch the latest changes
		fmt.Println("Fetching latest changes...")
		err = repo.Fetch(&git.FetchOptions{
			Auth:     auth,
			Progress: os.Stdout,
		})
		if err != nil && err != git.NoErrAlreadyUpToDate {
			log.Fatalf("Failed to fetch latest changes: %v", err)
		}

		// Checkout the specified branch
		worktree, err := repo.Worktree()
		if err != nil {
			log.Fatalf("Failed to get worktree: %v", err)
		}

		fmt.Println("Checking out branch:", branch)
		err = worktree.Checkout(&git.CheckoutOptions{
			Branch: plumbing.NewBranchReferenceName(branch),
			Force:  true,
		})
		if err != nil {
			log.Fatalf("Failed to checkout branch: %v", err)
		}
	}

	// Change working directory to the cloned repository
	if err := os.Chdir(repoPath); err != nil {
		log.Fatalf("Failed to change directory: %v", err)
	}

	// Run Gradle build
	fmt.Println("Running Gradle build...")
	if err := runCommand("./gradlew", "build"); err != nil {
		log.Fatalf("Failed to build project: %v", err)
	}

	fmt.Println("Build completed successfully.")
}
func runCommand(name string, args ...string) error {
	cmd := exec.Command(name, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}
